/*
	mysql C++ wrapper library

	Author: Roland Haenel <rh@ginster.net>

	This program is in the public domain.
	Distribute and use it freely.
*/

#ifndef __DB_MYSQL_H__
#define __DB_MYSQL_H__


#ifdef __MYSQL__

#include <stdio.h>
#include <stdlib.h>
#include <time.h>		
#include <string.h>

#ifdef WIN32
#include <windows.h>
#else
#include <pthread.h>
#endif

#include <mysql.h>

#include "RtDefines.h"

#define DB_SUCCESS								0
#define DB_ERROR									5000
#define DB_FAIL_INITIALIZE_PROCESS_ENVIRONMENT	DB_ERROR +1
#define DB_FAIL_FREE_ENVIRONMENT_HANDLE			DB_ERROR +2
#define DB_FAIL_INVALID_DATATYPE					DB_ERROR +3
#define DB_FAIL_CLOSE_SESSION						DB_ERROR +4
#define DB_OCINUMBER_IS_INTEGER					DB_ERROR +5


#define _MAX_DBLENGTH           256

#define _MAX_SQLLENGTH          16384
#define _MAX_ERRMESSAGE	1024

class CDBException_
{
public:
	CDBException_();
	~CDBException_();

public:
	void SetErrorString(short nRetCode, LPCSTR lpszError);
	void Empty();

public:
	int	m_nRetCode;
	BYTE	m_szError[_MAX_ERRMESSAGE];
};

void _DB_ThrowException(short nRetCode, LPCSTR lpszError);

class CRecordset_;

class CDatabase_
{
	friend class CRecordset_;
public :
	CDatabase_();
	~CDatabase_();

public :
	/* called to establishes a connection to a database data source */
	/* try...catch... */
	int  Open( LPBYTE dbserver, LPBYTE database, 
			LPBYTE username, LPBYTE password,
			BOOL  bReadOnly=FALSE );

	/* called to closes the data source connection */
	/* try...catch... */
	int  Close();

	/* called to executes a sql statement, an sql stored procedure or
	   an sql stored function, with or without sql stored package */
	/* try...catch... */
	int  ExecuteSQLDirect( LPCSTR sql_stmt, 
			CRecordset_ *pResultset=NULL,
			BOOL bRemote = FALSE);
	
	int InsertAutoIncRow(LPCSTR sql_stml,
						LONGLONG& autoNumber);

protected:
	int Open();
private :
	BOOL		m_bReadOnly;	/* not support */
	CRtString	m_dbserver;
	CRtString	m_database;
	CRtString	m_username;
	CRtString	m_password;
	int			m_port;
	MYSQL*		m_mysql;
	BOOL		m_bConnected;
};

class CRecordset_
{
public:
	CRecordset_(CDatabase_* pDB);
	~CRecordset_();
	int Destroy();
	int FillResultSet(BOOL bRemote);
	int GetRecordCount(){return m_RecordCount;}
	int GetColumnCount(){return m_ColumnCount;}
	int GetAffectRows(){return m_AffectRows;}
	MYSQL_ROW	GetRecord(DWORD dwIndex);
protected:
	CDatabase_*	m_pDB;
	MYSQL_RES*	m_result;
	//MYSQL_ROW	m_row;
	BOOL	m_bRemote;
	int		m_RecordCount;
	int		m_ColumnCount;
	int		m_AffectRows;
};

#endif //__MYSQL__
#endif
